#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>

__thread int g_val = 100;

std::string changeId(const pthread_t &thread_id)
{
    char tid[128];
    snprintf(tid, sizeof(tid), "0x%x", thread_id);
    return tid;
}

void *start_routine(void *args)
{
    // 安全类型转换
    std::string threadname = static_cast<const char *>(args);
    while (true)
    {
        std::cout << threadname << " running ... : " << changeId(pthread_self()) <<" g_val: "<< g_val << " &g_val: " << &g_val << std::endl;
        sleep(1);
        g_val++;
    }
}

int main()
{
    // 在之前的学习中，我们了解到线程需要被等待join 否则会内存泄漏
    // 不想进行线程等待是否可以？ --可以 将线程分离即可

    pthread_t tid;
    pthread_create(&tid, nullptr, start_routine, (void *)"thread 1");
    // pthread_self 函数获取自身的线程标识符(tid)
    std::string main_id = changeId(pthread_self());
    // 线程分离 -- detach
    // pthread_detach(tid);
    // std::cout << "main thread running ... new thread id: " << changeId(tid) <<" main thread id: " << main_id << std::endl;

    while (true)
    {
        std::cout << "main thread running ... new thread id: " << changeId(tid) << " main thread id: " << main_id << " g_val: " << g_val << " &g_val: " << &g_val << std::endl;
        sleep(1);
    }

    int n = pthread_join(tid, nullptr);
    std::cout << "result: " << n << " : " << strerror(n) << std::endl;
    return 0;
}
